package com.chongba.schedule.jdk;

import java.util.Calendar;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HanWen
 * @Date: 2020/3/11 19:58
 */
public class DelayedDemo implements Delayed {

    private int executeTime;

    public DelayedDemo (int delay){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,delay);
        this.executeTime = (int) (calendar.getTimeInMillis()/1000);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        int delay = executeTime - (int)(System.currentTimeMillis()/1000);
        return delay;
    }

    @Override
    public int compareTo(Delayed o) {
        long l = this.getDelay(TimeUnit.SECONDS) - o.getDelay(TimeUnit.SECONDS);
        return l==0? 0 :( l < 0 ? -1:1);
    }

    public static void main(String[] args) {
        DelayQueue<Delayed> queue = new DelayQueue<>();
        //添加任务
        System.out.println("开始消费");
        queue.add(new DelayedDemo(5));
        queue.add(new DelayedDemo(10));
        queue.add(new DelayedDemo(15));

        while (queue.size()!=0){
            Delayed task = queue.poll();
            if (task != null){
                System.out.println(System.currentTimeMillis()/1000 +"消费了");
            }
            //每隔1s消费一次
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
